package j20251112;

import java.util.concurrent.Semaphore;

public class Demo9 {
    public static void main(String[] args) {
        // 4 个线程同时访问, 但是只有 4 个线程能够获取到资源
        Semaphore semaphore = new Semaphore(4);
        Runnable runnable = new Runnable() {
            // 每个线程执行的任务
            @Override
            public void run() {
                try {
                    System.out.println("申请资源");
                    // 申请资源
                    semaphore.acquire();
                    System.out.println("我获取到资源了");
                    Thread.sleep(1000);
                    System.out.println("我释放资源了");
                    // 释放资源
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(runnable);
            t.start();
        }
    }
}
